package com.lagou.homework144;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class ClientRunnable implements Runnable {

    @Override
    public void run() {
        Scanner scanner = null;
        Socket socket = null;
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        try {
            socket = new Socket("127.0.0.1", 8888);
            System.out.println("客户端：成功连接到服务器！");
            objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectInputStream = new ObjectInputStream(socket.getInputStream());
            while (true) {
//                    Thread.sleep(1000);
                System.out.println("客户端：请输入登录名和密码：");
                scanner = new Scanner(System.in);
                String us = scanner.next();
                String pwd = scanner.next();

                objectOutputStream.writeObject(new UserMessage("check", new User(us, pwd)));

                Object obj = objectInputStream.readObject();
                System.out.println("客户端：收到服务端消息 " + obj);

                if (obj instanceof UserMessage) {
                    if (((UserMessage) obj).getType().equalsIgnoreCase("success")) {
                        System.out.println("-------登陆成功---------");
                        break;
                    } else System.out.println("------登陆失败---------");
                }

            }

//                socket.shutdownOutput();
//                socket.shutdownInput();

        } catch (IOException | ClassNotFoundException e) {
            System.out.println(e.getClass());
            e.printStackTrace();
        } finally {
            try {
                if (socket != null)
                    socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
